﻿#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql.h>

static inline void check(MYSQL * con) 
{
	fprintf(stderr, "%s\n", mysql_error(con));
	mysql_close(con);
	exit(EXIT_FAILURE);
}

int main(int argc, char * argv[]) 
{
	MYSQL * con = mysql_init(NULL);
	if (NULL == con) {
		fputs("main mysql_init NULL == con! error !\n", stderr);
		exit(EXIT_FAILURE);
	}

	if (!mysql_real_connect(con, "localhost", "root", "", "transaction", 0, NULL, 0))
		check(con);

	puts("Mariadb is connect and run succesed.");

	if (mysql_query(con, "select * from test;"))
		check(con);

	MYSQL_RES * res = mysql_store_result(con);
	if (NULL == res)
		check(con);

	MYSQL_ROW row;
	unsigned rlen = mysql_num_fields(res);
	printf("Table [test] row length is %u.\n", rlen);

	while ((row = mysql_fetch_row(res))) {
		for (unsigned i = 0; i < rlen; ++i)
			printf("%s ", row[i]);
		putchar('\n');
	}

	mysql_free_result(res);
	mysql_close(con);

	getchar();
	return 0;
}